<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="80px" size="mini">
      <el-form-item label="入库单号" prop="warehousingNo">
        <el-input v-model="queryParams.warehousingNo" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="单据号" prop="procureOdd">
        <el-input v-model="queryParams.procureOdd" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="供商名称" prop="supplierName">
        <el-input v-model="queryParams.supplierName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="入库状态" prop="warehousingStatus">
        <el-select v-model="queryParams.warehousingStatus" clearable placeholder="请选择">
          <el-option key="1" label="待入库" value="1"/>
          <el-option key="2" label="已入库" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入库时间" prop="warehousingTime">
        <el-date-picker v-model="dateRange" end-placeholder="结束日期" range-separator="-" start-placeholder="开始日期" style="width: 240px" type="daterange" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['erp:ErpWarehousing:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">列表导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ErpWarehousingList" row-key="warehousingId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" align="center" :reserve-selection="true" width="50" />
      <el-table-column align="center" label="入库单号" prop="warehousingNo" sortable/>
      <el-table-column align="center" label="单据号" prop="procureOdd" sortable/>
      <el-table-column align="center" label="供商/客户" prop="supplierOrCustomerName" width="250px;"/>
      <el-table-column align="center" label="入库类型" prop="warehousingType" sortable width="120px;">
        <template slot-scope="scope">
          <span v-if="scope.row.warehousingType == 1">采购</span>
          <span v-if="scope.row.warehousingType == 2">销售退换</span>
          <span v-if="scope.row.warehousingType == 3">采购退换</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="入库仓库" prop="wareName" sortable width="120px;"/>
      <el-table-column align="center" label="预计入库量" prop="answerScheduledReceipt"  width="100px;"/>
      <el-table-column align="center" label="实际入库量" prop="actualNumber"  width="100px;">
      </el-table-column>
      <el-table-column align="center" label="入库状态" prop="warehousingStatus" sortable width="120px;">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.warehousingStatus == 1" type="danger">待入库</el-tag>
          <el-tag v-if="scope.row.warehousingStatus == 2" type="success">已入库</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="入库人" prop="nickName"  width="100px;"/>
      <el-table-column align="center" label="联系电话" prop="phonenumber" width="120px;"/>
      <el-table-column align="center" label="入库时间" prop="warehousingTime" sortable width="180px;">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.warehousingTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建人" prop="createName" width="100px;"/>
      <el-table-column align="center" label="备注" prop="remark"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.warehousingStatus == 1" v-hasPermi="['erp:ErpWarehousing:warehouse']" size="mini" type="text" @click="handleWarehouse(scope.row)">入库</el-button>
          <el-button v-hasPermi="['erp:ErpWarehousing:view']" size="mini" type="text" @click="handleViewOrPrint(scope.row,1)">查看</el-button>
          <el-button v-hasPermi="['erp:ErpWarehousing:print']" size="mini" type="text" @click="handleViewOrPrint(scope.row,3)">打印</el-button>
          <el-button  size="mini" type="text" @click="handleExportDetails(scope.row)" v-hasPermi="['erp:ErpWarehousing:export']">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改采购入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="80%">
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px" size="mini">
        <el-row :gutter="15">
          <el-col :span="4">
            <el-form-item label="单据号" prop="procureOdd">
              <el-input v-model="form.procureOdd" :disabled="true" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="供应商" prop="supplierOrCustomerName">
              <el-input v-model="form.supplierOrCustomerName" :disabled="true" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库仓库" prop="wareId">
              <treeselect v-model="form.wareId" :normalizer="normalizer" :options="wareOptions" placeholder="请选择"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库人员" prop="warehousingPerson">
              <el-select v-model="form.warehousingPerson" filterable placeholder="请选择" @change="handleSelectedUser">
                <el-option v-for="item in personOptions" :key="item.userId" :label="item.nickName" :value="item.userId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="联系电话">
              <el-input v-model="form.phonenumber" :disabled="true" placeholder="请输入"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-table v-loading="loading" :data="form.detailsList" border>
            <el-table-column align="center" label="商品编号" prop="supplierCommodityNo"/>
            <el-table-column align="center" label="商品名称" prop="supplierCommodityName"/>
            <el-table-column align="center" label="商品类别" prop="commodityType"/>
            <el-table-column align="center" label="规格" prop="supplierCommoditySpec"/>
            <el-table-column align="center" label="单位" prop="supplierCommodityUnit"/>
            <el-table-column align="center" label="入库单位" prop="commodityUnitId">
              <template slot-scope="scope">
                <el-select v-model="scope.row.commodityUnitId" placeholder="请选择" @change="handleTableRowSelectChange($event, scope.row)">
                  <el-option v-for="item in scope.row.unitList" :key="item.commodityUnitId" :label="item.unitName1" :value="item.commodityUnitId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位关系" prop="unitRelationship"/>
            <el-table-column align="center" label="换算结果" prop="unitResult"/>
            <el-table-column align="center" label="采购数量" prop="procureNumber"/>
            <el-table-column align="center" label="本期入库" prop="thisIssue">
              <template slot-scope="scope">
                <el-input v-numberOnly v-model="scope.row.thisIssue"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="已入库" prop="realityNumber">
              <template slot-scope="scope">
                {{ !scope.row.realityNumber ? 0 : scope.row.realityNumber }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="viewOpen" append-to-body title="采购入库" width="80%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="medium">
        <div id="printRKForm">
          <div class="title">
            湖南胜博清洁服务有限公司（入库单）
          </div>
          <div class="head-print">
            <div>入库单号：{{ form.warehousingNo }}</div>
            <div>单据号：{{ form.procureOdd }}</div>
            <div>供应商：{{ form.supplierOrCustomerName }}</div>
            <div>入库仓库：{{ form.wareName }}</div>
          </div>
          <div class="head-print">
            <div>入库人员：{{ form.nickName }}</div>
            <div>入库日期：{{
                parseTime(form.warehousingTime, '{y}年{m}月{d}日')
              }}</div>
          </div>
          <right-toolbar :columns="columns" :refresh="false" :search="false" class="no-print"></right-toolbar>
          <table class="table_print">
            <tr>
              <th v-if="columns[0].visible" width="80px">序号</th>
              <th v-if="columns[1].visible">商品编号</th>
              <th v-if="columns[2].visible">商品名称</th>
              <th v-if="columns[3].visible">商品类别</th>
              <th v-if="columns[4].visible">规格</th>
              <th v-if="columns[5].visible">单位</th>
              <th v-if="columns[6].visible">单位关系</th>
              <th v-if="columns[7].visible">采购数量</th>
              <th v-if="columns[8].visible">本期入库</th>
              <th v-if="columns[9].visible">已入库</th>
            </tr>
            <tr v-for="(item,index) in form.detailsList" :key="index">
              <td v-if="columns[0].visible">{{index + 1}}</td>
              <td v-if="columns[1].visible">{{item.supplierCommodityNo}}</td>
              <td v-if="columns[2].visible">{{item.supplierCommodityName}}</td>
              <td v-if="columns[3].visible">{{item.commodityType}}</td>
              <td v-if="columns[4].visible">{{item.supplierCommoditySpec}}</td>
              <td v-if="columns[5].visible">{{item.unitName1}}</td>
              <td v-if="columns[6].visible">{{item.unitRelationship}}</td>
              <td v-if="columns[7].visible">{{item.procureNumber}}</td>
              <td v-if="columns[8].visible">{{item.realityNumber}}</td>
              <td v-if="columns[8].visible">{{!item.realityNumber ? 0 : item.realityNumber }}</td>
            </tr>
          </table>
          <div class="head-print-2">
            <div>制单人：{{ $store.getters.nickName}}</div>
            <div style="text-align: right; padding-right: 20px;">合计数量：{{ form.sumNumber }}</div>
          </div>
          <div class="single-line-print">单据备注：{{ form.remark }}</div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type == 3" v-print="'#printRKForm'" type="primary">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addErpWarehousing, getErpWarehousing, listErpWarehousing, updateErpWarehousing} from "@/api/erp/ErpWarehousing";
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import {getSysUserList} from '@/api/system/user'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ErpWarehousing",
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 多选ids
      ids: [],
      // 日期范围
      dateRange: [],
      // 采购入库表格数据
      ErpWarehousingList: [],
      // 是否显示弹出层
      open: false,
      title: '',
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehousingNo: null,
        procureOdd: null,
        supplierName: null,
        warehousingStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        wareId: [
          {required: true, message: "仓库不能为空", trigger: "blur"}
        ],
        procurePersonId: [
          {required: true, message: "采购人不能为空", trigger: "blur"}
        ],
      },
      // 仓库
      wareOptions: [],
      // 采购人
      personOptions: [],
      type: 1,
      // 打印列
      columns: [
        {key: 0, label: `序号`, visible: true},
        {key: 1, label: `商品编号`, visible: true},
        {key: 2, label: `商品名称`, visible: true},
        {key: 3, label: `商品类别`, visible: true},
        {key: 4, label: `单位`, visible: true},
        {key: 5, label: `规格`, visible: true},
        {key: 6, label: `单位关系`, visible: true},
        {key: 7, label: `采购数量`, visible: true},
        {key: 8, label: `本期入库`, visible: true},
        {key: 9, label: `已入库`, visible: true}
      ]
    };
  },
  created() {
    this.getList();
    this.handleGetListSysUser();
    this.getTreeselect();
  },
  methods: {
    /** 查询采购入库列表 */
    getList() {
      this.loading = true;
      listErpWarehousing(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.ErpWarehousingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.warehousingId)
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then(res => {
        this.personOptions = res.data;
      })
    },
    // 入库人选择回调
    handleSelectedUser(e) {
      let obj = this.personOptions.find(i => {
        return i.userId == e
      })
      this.form.phonenumber = obj.phonenumber;
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        warehousingId: null,
        procureId: null,
        procureOdd: null,
        wareId: null,
        warehousingNo: null,
        warehousingStatus: null,
        warehousingPerson: null,
        warehousingTime: null,
        answerScheduledReceipt: null,
        warehousingType: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleWarehouse(row) {
      this.reset();
      const warehousingId = row.warehousingId || this.ids
      getErpWarehousing(warehousingId).then(response => {
        this.form = response.data;
        this.title = "入库单号：" + this.form.warehousingNo;
        this.open = true;
      });
    },
    /** 查看 */
    handleViewOrPrint(row, type) {
      this.type = type;
      const warehousingId = row.warehousingId || this.ids
      getErpWarehousing(warehousingId).then(response => {
        this.form = response.data;
        this.form.sumNumber = 0;
        this.form.detailsList.forEach(i => {
          this.form.sumNumber += i.realityNumber
        })
        this.viewOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.warehousingId != null) {
            updateErpWarehousing(this.form).then(response => {
              this.$modal.msgSuccess("入库成功");
              this.open = false;
              this.getList();
            });
          } else {
            addErpWarehousing(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
     // 商品单位选择
     handleTableRowSelectChange(e, row) {
      let obj = row.unitList.find(item => {
        return item.commodityUnitId == e
      })
      row.unitResult = obj.unitResult;
      row.unitRelationship = obj.unitRelationship;
    },
    /** 计算入库量 */
    calculateWarehouse(list) {
      return list.reduce((total, item) => total + item.realityNumber, 0)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/ErpWarehousing/export', {
        ...this.queryParams,
        exportIds: this.ids?.join(',')
      }, `采购入库_${new Date().getTime()}.xlsx`)
    },
    // 导出
    handleExportDetails(row){
      this.download('erp/ErpWarehousing/exportDetails/' + row.warehousingId, {}, `采购入库_${row.warehousingNo}.xlsx`)
    }
  }
};
</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.title {
  padding: 10px;
  text-align: center;
  font-size: 32px;
  font-weight: 500;
}

.oddInfo {
  font-size: 16px;
}

.remark {
  padding-top: 10px;
  padding-bottom: 10px;
}

table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
